package com.Utils;

import com.Pojo.User;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by XingYang on 2019/3/6.
 */
@Component
public class RedisUtil {

    private RedisUtil redisUtil =null;
    public RedisUtil RedisUtil() {
        if(redisUtil==null){
            this.redisUtil = new RedisUtil();
            return redisUtil;
        }
        return redisUtil;
    }





    public Jedis getClient(){

            return new Jedis("127.0.0.1");

    }
/**
 * 序列化对象并返回序列化之后的字节数组
 * */
    public byte[] serializeObj(Object obj) {
        if(obj == null)
            return null;

        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

            objectOutputStream.writeObject(obj);
        }catch (IOException e){
            e.printStackTrace();
        }

        return byteArrayOutputStream.toByteArray();

    }


    /**
     * 读取字节数组并返回反序列化后的对象
     * */
    public Object unSerializseObj(byte[] bytes){
        if (bytes == null)
            return null;
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;

        try{
            byteArrayInputStream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return objectInputStream.readObject() ;

        }catch (Exception e ){
            e.printStackTrace();
        }
        return null;
    }


    public void refreshUser(){
        User user = new User();
        user.setUsername("tom");
        List<User> userList = new LinkedList<>();
        userList.add(user);
        Jedis jedis = getClient();


        User user1 = new User();
        user1.setUsername("mac");

        jedis.lpush("users",user.toString());
        jedis.lpush("users",user1.toString());


        System.out.println(jedis.lrange("users",0,2));

    }

    public static void main (String[] args){

        RedisUtil re = new RedisUtil();
        Jedis j = re.getClient();
        User user = new User();


        user = (User)(re.unSerializseObj(j.lrange("zhang".getBytes(),0,0).get(0)));

        System.out.println(user.toString());


    }
}
